import Time from './Time.js';
import Slide from './Slide.js';
import Util from '../Util.js';
import Msg from './Message.js';
import Win from './Win.js';
import Http from './Http.js';

let sysSetting;

try {
    sysSetting = JSON.parse(window.localStorage['sysSetting']);

} catch {
    sysSetting = {
        '00': {
            iconfont: 'fas fa-map-marker-alt',
            name: '定位',
            checked: ''
        },
        '01': {
            iconfont: 'fas  fa-charging-station',
            name: '节电模式',
            checked: 'checked'
        },
        '02': {
            iconfont: 'fab fa-bluetooth-b',
            name: '蓝牙',
            checked: ''
        },
        '03': {
            iconfont: 'fas fa-sun',
            name: '夜间模式',
            checked: ''
        },
        '04': {
            iconfont: 'fas fa-satellite-dish',
            name: '移动热点',
            checked: ''
        },
        '05': {
            iconfont: 'fas fa-plane',
            name: '飞行模式',
            checked: 'checked'
        },
        '06': {
            iconfont: 'fas fa-podcast',
            name: '就近共享',
            checked: ''
        },
        '07': {
            iconfont: 'fas fa-tools',
            name: '所有设置',
            checked: ''
        },
        '08': {
            iconfont: 'fas fa-broadcast-tower',
            name: '网络',
            checked: ''
        },
        '09': {
            iconfont: 'fas fa-link',
            name: '连接',
            checked: ''
        },
        '10': {
            iconfont: 'fas fa-chalkboard',
            name: '投影',
            checked: ''
        },
        '11': {
            iconfont: 'fas fa-rss',
            name: 'VPN',
            checked: ''
        },
        '12': {
            iconfont: 'fas fa-moon',
            name: '专注助手',
            checked: 'checked'
        },
        '13': {
            iconfont: 'fas fa-cut',
            name: '屏幕截图',
            checked: ''
        },
        '14': {
            iconfont: 'fas fa-wifi',
            name: 'WLAN',
            checked: ''
        },
        '15': {
            iconfont: 'fas fa-users',
            name: 'YunGo',
            checked: ''
        },
        '16': {
            iconfont: 'fas fa-sun',
            name: '',
            value: .5
        }
    };
    // window.localStorage['sysSetting'] = JSON.stringify(sysSetting);
    // new Msg({ icon: './images/windows.png' }, '已将系统设置为默认配置并保存至本地！');
}




/**
 * 对任务栏图标进行设置，使其不受聚焦桌面后的影响，点击仍然有效
 * 在所有任务栏图标点击事件在必须使用，
 * 
 * @param {Event} event
 * @param {HTMLElement} ctrl 控制该图标弹出事件的input控件
 */
function _prevent(event, ctrl) {
    if (ctrl.checked) {
        event.preventDefault();
        desktop.clearDesktopCheck.checked = true;
    }
}

let desktop = null;

let tasksContainer = null;

export default class TaskBar {

    constructor(dp) {

        desktop = dp;
        // 通知中心设置
        const msgCenterBtn = document.querySelector('#msgCenterBtn');
        const msgCenterCtrl = document.querySelector('#msgCenterCtrl');
        msgCenterBtn.addEventListener('click', (event) => {
            _prevent(event, msgCenterCtrl);
        });

        // 生成通知中心设置项
        builtMsgCenterItems('#msgCenterItemContainer');

        const clearAllMsg = document.querySelector('#clearAllMsg');
        clearAllMsg.addEventListener('click', () => {
            Msg.clear();
        });

        const taskBar = document.querySelector('#taskBar');

        // 点击任务栏时，去掉桌面图标的选中状态
        taskBar.addEventListener('click', () => {
            desktop.desktopCtrl.checked = true;
        });

        // 日历部分的设置
        // const date = new Date();
        const time = new Time(new Date());

        // 日历部分时间设置
        time.setTime('#timeOnTaskBar', new Date());
        time.setTime('#timeOnDatePanel', new Date(), true);
        time.setDate('#dayOnDatePanel');
        time.setMonth('#monthOnDatePanel');
        time.setCalendar();
        time.bindCtrl('preMonth', 'nextMonth');

        const timeOnTaskBarBtn = document.querySelector('#timeOnTaskBarBtn');
        const calendarCtrl = document.querySelector('#calendarCtrl');
        timeOnTaskBarBtn.addEventListener('click', (event) => {
            _prevent(event, calendarCtrl);

            // 每次点开日历面板都会重置到当前时间
            time.date.setTime(Date.now());
            time.setCalendar();
            time.setMonth('#monthOnDatePanel');
        });

        // 显示桌面按钮
        const showDesktop = document.getElementById('showDesktop');
        showDesktop.addEventListener('mouseover', (event) => {
            Win.showWinOutline(dp);
        });

        showDesktop.addEventListener('mouseleave', (event) => {
            Win.restoreFromTransparent(dp);
        });

        showDesktop.addEventListener('click', (event) => {
            Win.minimizeAll(dp);
        });

        tasksContainer = document.querySelector('#tasksContainer');

        // 任务栏图标点击事件
        tasksContainer.addEventListener('click', (event) => {
            const target = Util.getTarget(event, 'LI', 'IMG', 'SPAN');

            if (target) {
                const id = target.id.substring(target.id.length - 3);
                const win = document.getElementById(`win_${id}`);
                if (win && Win.isOnTop(id)) {
                    const app = dp.app[id];
                    if (app.cache.status === 'maximize' || app.cache.status === 'normal') {
                        Win.minimize(id);
                        dp.app[id].cache.level = 1;
                    } else {
                        Win.restore(win);
                    }
                } else {
                    Win.open(dp, id);
                }
            }
        });

        tasksContainer.addEventListener('mouseover', (event) => {
            const target = Util.getTarget(event, 'LI', 'IMG', 'SPAN');

            if (target) {
                const id = target.id.substring(target.id.length - 3);
                Win.showWinOutlineExcept(dp, id);
            }
        });

        tasksContainer.addEventListener('mouseleave', (event) => {
            Win.restoreFromTransparent(dp);
        });
    }

    static addTask(id) {
        const tasksContainer = document.querySelector('#tasksContainer');
        const app = desktop.app[id];

        if (app.onTaskBar !== true) {
            const li = document.createElement('li');
            li.className = 'task-item';
            li.id = `taskbar_${id}`;
            li.title = app.name;

            li.setAttribute('data-taskbar', id);
    
            li.innerHTML = `
                <img data-taskbar="${id}" src="${app.icon}" alt="">
                <span data-taskbar="${id}" class="current" id="runingTask_${id}"></span>
                `;
            tasksContainer.appendChild(li);
    
            li.setAttribute('style', 'opacity: 0');
            Util.animate(li, {
                opacity: 1,
            });
        }
    }

    static removeTask(id, flag) {
        const task = document.getElementById(`taskbar_${id}`);
        
        if (flag === false) {
            desktop.app[id].onTaskBar = false;
            task.remove();
        } else {
            Util.animate(task, {
                opacity: 0,
            }, () => {
                Util.animate(task, {
                    width: 0,
                }, () => {
                    if (desktop.app[id]) {
                        desktop.app[id].onTaskBar = false;
                    } 
                    task.remove();
                });
            }, 1);
        }
    }

    static hide() {
        let flag = true;
        for (let id in desktop.app) {
            if (desktop.app[id].cache && desktop.app[id].cache.status === 'maximize') {
                flag = false;
                break;
            }
        }

        if (!flag) {
            const taskBar = document.getElementById('taskBar');
            Util.animate(taskBar, {
                height: 0.26,
                backgroundColor: 'rgba(19, 19, 19, .5)'
            }, null, 0.4);
            taskBar.onmouseover = function() {
                Util.animate(taskBar, {
                    height: 3.26,
                }, null, 0.4);
            }
    
            taskBar.onmouseleave = function() {
                Util.animate(taskBar, {
                    height: 0.26,
                }, null, 0.4);
            }
        }   
    }

    static show() {

        let flag = true;
        for (let id in desktop.app) {
            if (desktop.app[id].cache && desktop.app[id].cache.status === 'maximize') {
                flag = false;
                break;
            }
        }

        if (flag) {
            const taskBar = document.getElementById('taskBar');
            Util.animate(taskBar, {
                height: 3.26,
                backgroundColor: 'transparent'
            }, null, 0.4);
    
            taskBar.onmouseover = null;
            taskBar.onmouseleave = null;
        }
    }

    static fixToTaskBar(desktop, id) {
        const li = document.createElement('li');
        const app = desktop.app[id];
        let isOn = Win.isOn(desktop, id);
        if (!document.getElementById(`taskbar_${id}`)) {
            li.innerHTML = `
                <li data-taskbar="${id}" class="task-item" id="taskbar_${id}" title="${app.name}" style="opacity: 0; width: 0">
                    <img data-taskbar="${id}" src="${app.icon}" alt="">
                    <span data-taskbar="${id}"  id="runingTask_${id}" class="${isOn ? 'current' : ''}"></span>
                </li>`;
            Util.prependChild(tasksContainer, li);
            Util.animate(li.children[0], {
                opacity: 1,
                width: 2.61,
            });
            app.onTaskBar = true;
        } else if(isOn) {
            app.onTaskBar = true;
        }
        // 上传数据
        Http.upload('app', desktop.app);
    }

    static removeFromTaskBar(desktop, id) {
        const app = desktop.app[id];
        app.onTaskBar = false;

        // 上传数据
        Http.upload('app', desktop.app);

        if (!Win.isOn(desktop, id)) {
            TaskBar.removeTask(id);
        }
    }

    static isOnTaskBar(id) {
        const app = desktop.app[id];
        return app.onTaskBar;
    }

    // flag表示是否设置背景样式
    static setTopWinTask(flag) {
        // const id = Win.getTopWin();
        // // 在最顶层时，任务栏图标需要有背景色
        // const taskItems = document.querySelectorAll('.task-item');

        // let temp;
        // for (let i = 0; i < taskItems.length; i++) {
        //     taskItems[i].className = 'task-item';
        //     const id = taskItems[i].id.substring(taskItems[i].id.length - 3);
        //     const app = desktop.app[id];

        //     if (!app.onTaskBar && (JSON.stringify(app.cache) !== '{}' || app.cache.status !== 'cached')) {
        //         taskItems[i].children[1].className = 'current';
        //         temp = app;
        //     }
        // }

        // if (!flag) {
        //     const current = document.getElementById(`taskbar_${id}`);
        //     if (temp && !temp.onTaskBar && (JSON.stringify(temp.cache) !== '{}' || temp.cache.status !== 'cached')) {
        //         current.className = 'task-item top';
        //         current.children[1].className = 'current current-top';
        //     }
        // }
    }
    
    static saveSetting() {
        window.localStorage['sysSetting'] = JSON.stringify(sysSetting);
    }
}

function builtMsgCenterItems(idSelector) {
    const msgCenterItemContainer = document.querySelector(idSelector);

    let HTMLString = '';
    // 循环生成设置项
    // 最后一个是亮度控制信息，不循环，单独设置
    for (let i = 0; i < 16; i++) {
        if (sysSetting[Util.addZero(i, 2)].checked !== '') {
            HTMLString += `
            <label>
                <input type="checkbox" checked="${sysSetting[Util.addZero(i, 2)].checked}">
                <li data-sysIndex="${Util.addZero(i, 2)}"><i class="${sysSetting[Util.addZero(i, 2)].iconfont}"></i>${sysSetting[Util.addZero(i, 2)].name}</li>
            </label>
            `;
        } else {
            HTMLString += `
            <label>
                <input type="checkbox">
                <li data-sysIndex="${Util.addZero(i, 2)}"><i class="${sysSetting[Util.addZero(i, 2)].iconfont}"></i>${sysSetting[Util.addZero(i, 2)].name}</li>
            </label>
            `;
        }
    }

    msgCenterItemContainer.children[0].innerHTML = HTMLString;

    msgCenterItemContainer.children[0].addEventListener('click', (event) => {

        let target = Util.getTarget(event, 'LI', 'I');

        // 这里进行处理
        if (target) {
            // 获取当前点击对象
            const index = target.getAttribute('data-sysIndex');

            // 存入值
            if (sysSetting[index].checked === '') {
                sysSetting[index].checked = 'checked';
            } else {
                sysSetting[index].checked = '';
            }
            // 写入本地储存 
            TaskBar.saveSetting();
        }

        return false;
    });

    // 添加亮度控制条
    new Slide('brightCtrl', sysSetting['16'].value, (slide, sysSetting) => {
        // 保存对象并写入本地储存
        sysSetting['16'].value = slide.value;
        TaskBar.saveSetting();
    }, sysSetting);
}
